#!/usr/bin/env python3
# Copyright (c) 2020-2021 maminjie <maminjie1@huawei.com>
# SPDX-License-Identifier: MulanPSL-2.0

"""
This is an openeuler helper script for working with gitee.com
"""

import sys
import os
import base64
import yaml
import configparser

from oec.libs import gitee

class OpenEuler(gitee.Gitee):
    """
    openeuler helper
    """
    def __init__(self, token=None):
        if token is None:
            conf_file = os.path.expanduser("~/.oecrc")
            if os.path.isfile(conf_file):
                conf = configparser.ConfigParser()
                conf.read(conf_file)
                token = conf.get("gitee", "token")
            else:
                print("ERROR: ~/.oecrc is not exist")
                sys.exit(1)
        super(OpenEuler, self).__init__(token)

    def get_yaml(self, pkg, branch="master"):
        """Get upstream yaml metadata for specific package"""
        path = "{repo}.yaml".format(repo=pkg)
        resp = super(OpenEuler, self).get_contents("src-openeuler", pkg, path, branch)
        if not resp:
            print("WARNING: {}.yaml can't be found in {}/{}.".format(pkg, pkg, branch))
            return ''
        return base64.b64decode(resp["content"]).decode("utf-8")

    def get_spec(self, pkg, branch="master"):
        """Get upstream spec metadata for specific package"""
        path = "{repo}.spec".format(repo=pkg)
        resp = super(OpenEuler, self).get_contents("src-openeuler", pkg, path, branch)
        if not resp:
            print("WARNING: {}.spec can't be found in {}/{}.".format(pkg, pkg, branch))
            return ''
        return base64.b64decode(resp["content"]).decode("utf-8")

    def get_sigs(self):
        """Get upstream sigs"""
        sigs_url = "https://gitee.com/openeuler/community/raw/master/sig/sigs.yaml"
        resp = super(OpenEuler, self).get_request(sigs_url)
        if not resp:
            return {}
        sigs = yaml.load(resp, Loader=yaml.Loader)
        return sigs

    def fork_repo(self, src_owner, dst_owner, repo):
        """Fork the repo from src_owner to dst_owner"""
        if super(OpenEuler, self).get_one_repo(dst_owner, repo):
            print("NOTE: {repo} was in {owner}".format(repo=repo, owner=dst_owner))
            return True
        if super(OpenEuler, self).fork_repo(src_owner, repo):
            return True
        else:
            return False
